from . import bp
from flask import render_template, flash, redirect, url_for, request
from app.models import User
from flask_login import login_user, logout_user, login_required
from app.backend.froms import LoginForm


@bp.route('/')
@bp.route('/index')
@login_required
def index():
    return render_template('backend/index.html')


@bp.route('/login', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.query.filter_by(username=form.username.data).first()
        if user is None or not user.check_password(form.password.data):
            flash('账号或密码错误,请重新输入!')
            return redirect(url_for('backend.login'))
        login_user(user)
        next_page = request.args.get('next')
        if next_page:
            return redirect(next_page)
        return redirect(url_for('backend.index'))
    return render_template('backend/login.html', form=form)


@bp.route('/logout')
def logout():
    logout_user()
    return redirect(url_for('backend.index'))
